﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace FillCartridgeBBB.Models
{
    public class PrinterRepository
    {
        private FillCartridgeDbEntities _db;

        public PrinterRepository (FillCartridgeDbEntities db)
        {
            _db = db;
        }

        public IEnumerable<Printer> SelectAll()
        {
            return _db.PrinterSet;
        }

        public Printer SelectById(int id)
        {
            return _db.PrinterSet.Include("Departments").First(p => p.PrinterId == id);
        }

        public IEnumerable<Printer> SelectByDepartment(Department department)
        {
            return
                _db.PrinterSet.Where(p => p.Departments.Any(d => d.DepartmentId == department.DepartmentId));
                    
        }

        public void Insert (Printer printer, string departments)
        {
            var deps = departments.Split(',');
            foreach (var departamentId in deps)
            {
                if (departamentId != "false")
                {
                    int id = int.Parse(departamentId);
                    Department departament = _db.DepartmentSet.First(dep => dep.DepartmentId == id);
                    printer.Departments.Add(departament);
                }
            }
            _db.AddToPrinterSet(printer);
            _db.SaveChanges();
        }

        public void Delete (int id)
        {
            _db.DeleteObject(SelectById(id));
            _db.SaveChanges();
        }

        public void Update(Printer printer, string departments)
        {
            Printer dbPrint = SelectById(printer.PrinterId);
            dbPrint.PrinterName = printer.PrinterName;
            dbPrint.CartridgeName = printer.CartridgeName;
            var deps = departments.Split(',');
            dbPrint.Departments.Clear();
            foreach (var departamentId in deps)
            {
                if (departamentId != "false")
                {
                    int id = int.Parse(departamentId);
                    Department departament = _db.DepartmentSet.Where(dep => dep.DepartmentId == id).First();
                    dbPrint.Departments.Add(departament);
                }
            }
            _db.SaveChanges();
        }
    }
}
